package com.kx.center.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.entity.Order;
import com.kx.center.entity.OrderDetail;
import com.kx.center.entity.query.QueryOrder;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.OrderService;
import com.kx.center.service.TradeOnlineService;
import com.kx.center.util.DateUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	OrderService service;
	@Autowired
	TradeOnlineService tradeOnlineService;

	@RequestMapping(value = "list/{storeId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String order_list(HttpServletRequest request, @PathVariable("storeId") Integer storeId) throws Exception {
		
		Integer page, pageSize, status;
		Date from = null, to = null;
		
		QueryOrder query = new QueryOrder();

		String storeIdStr = request.getParameter("store");
		String fromStr = request.getParameter("from");
		String toStr = request.getParameter("to");
		
		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");
		
		status = NumberUtils.toInt(request.getParameter("status"));
		page = NumberUtils.toInt(request.getParameter("page"));
		pageSize = NumberUtils.toInt(request.getParameter("pageSize"));
		
		if(DateUtil.isDate(fromStr))
			from = DateUtils.parseDate(fromStr, "yyyy-MM-dd");

		if(DateUtil.isDate(toStr))
			to = DateUtils.parseDate(toStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
		
		if(storeId <= 0)
			storeId = NumberUtils.toInt(storeIdStr);
		
		if(StringUtils.isBlank(sortBy))
			sortBy = "addtime";
		
		if(StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		query.setFrom(from);
		query.setTo(to);
		query.setStoreId(storeId);
		query.setStatus(status);
		query.setPage(page);
		query.setPageSize(pageSize);
		query.setSortBy(sortBy);
		query.setSortMethod(sortMethod);

		if (storeId > 0) {
			query.setStoreId(storeId);
		}
		
		query.setSortBy("addtime");
		query.setSortMethod("desc");

		QueryResult result = service.queryOrder(query);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String save_order(HttpServletRequest request) {
		String storeIdStr = request.getParameter("store_id");
		String orderIdStr = request.getParameter("order_id");
		String json = request.getParameter("data");

		Integer storeId = 0, oid = 0;

		if (StringUtils.isBlank(json)) {
			return Response.error(MessageCode.JSON_WRONG);
		}

		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

		try {
			data = (ArrayList<HashMap<String, Object>>) JSONParser.parse(json, data.getClass());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(MessageCode.JSON_WRONG);
		}

		if (storeIdStr != null && NumberUtils.isDigits(storeIdStr)) {
			storeId = NumberUtils.toInt(storeIdStr);
		}

		if (orderIdStr != null && NumberUtils.isDigits(orderIdStr)) {
			oid = NumberUtils.toInt(orderIdStr);
		}

		if (storeId == 0 && oid == 0)
			return Response.error(MessageCode.PARAMETER_WRONG);

		Order order = null;
		if (oid > 0) {
			order = service.findOrderById(oid);

			if (order == null || order.getStatus() != 1) {
				return Response.error(MessageCode.ORDER_ID_WRONG);
			}
		}

		service.saveOrder(storeId, order, data);

		return Response.success("数据提交成功");
	}

	@RequestMapping(value = "detail/{oid}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String oderDetail(HttpServletRequest request, @PathVariable("oid") Integer oid) {

		if (oid != null && oid > 0) {
			List<OrderDetail> orderDetails = service.findOrderDetailByOId(oid);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("data", orderDetails);
			return Response.success(map);
		} else {
			return Response.error(MessageCode.NO_DATA);
		}
		/*
		 * 名称: 订单详情 地址: /api/order/orderDetail 输入: [{id:1, oid: 'xx0001', sn:
		 * 'xx0001',goodsId:1,goodsSku:sku001,
		 * storeId:1,quantity:2,addtime:'',edittime:''}] 返回: {status: 'ok', msg:
		 * ''} 出错返回: {status: 'error', code: 100001, msg: '发生错误'}
		 */
	}

	@RequestMapping(value = "{oid}/confirm", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String confirm_order(HttpServletRequest request, @PathVariable("oid") Integer oid) {

		if (oid <= 0) {
			return Response.error(MessageCode.REQUEST_ERROR);
		} else {
			Order order = service.findOrderById(oid);

			if (order == null)
				return Response.error(MessageCode.ORDER_ID_WRONG);
			else {
				if (order.getStatus() != 1)
					return Response.error(MessageCode.OPERATOR_FAIL);
				else {
					order.setStatus(2);
					service.confirm(order);
					return Response.success();
				}
			}
		}
	}
	
}
